package vm

import (
	"bufio"
	"flag"
	"fmt"
	lua "github.com/yuin/gopher-lua"
	"github.com/yuin/gopher-lua/ast"
	"github.com/yuin/gopher-lua/parse"
	"os"
)

var (
	// lua 虚拟机池
	LuaVM *LStatePool
	Proto *lua.FunctionProto

	// 如果没有设置lua主单元的所在路径
	// 则默认在项目相对路径的
	LuaMainPath = "luasrc/main.lua"
)

// 写入变量事件
type LuaSetEvent = func(l *lua.LState)

//// CompileFile
//// 编译 lua 代码文件
func CompileFile(filePath string) (*lua.FunctionProto, error) {
	var (
		err   error
		file  *os.File
		chunk []ast.Stmt
		proto *lua.FunctionProto
	)
	file, err = os.Open(filePath)
	defer file.Close()
	if err != nil {
		return nil, err
	}
	reader := bufio.NewReader(file)
	chunk, err = parse.Parse(reader, filePath)
	if err != nil {
		return nil, err
	}
	proto, err = lua.Compile(chunk, filePath)
	if err != nil {
		return nil, err
	}
	return proto, nil
}

func init() {
	flag.Parse()

	// 新建虚拟机池
	LuaVM = NewLuaVMPool(1)
	var err error

	// 将lua脚本进行编译
	Proto, err = CompileFile(LuaMainPath)
	if err != nil {
		fmt.Println("加载lua脚本失败", err.Error())
	}
}
